<?php
class UsuarioBehavior extends CActiveRecordBehavior {
	private $owner;
	/**
	 * Permite la verificación de la clave.
	 * @param string $password clave del usuario.
	 * @return boolean verdadero cuando la validación del a clave es exitosa.
	 */
	public function validatePassword($password)
	{
		$this->owner = $this->getOwner();
		if(!is_string($password) || $password==='')
			return false;
		$password=md5($password);
		$test=($password==$this->owner->clave);
		return $test;
	}
	
	/**
	 * Mecanismo de cifrado de la clave.
	 * @param string $password clave del usuario.
	 * @return string clave cifrada.
	 */
	public function hashPassword($password)
	{
		$this->owner = $this->getOwner();
		$hash=md5($password);
	
		if(!is_string($hash))
			throw new CException(Yii::t('yii','Internal error while generating hash.'));
	
		return $hash;
	}
	/**
	 * Redefinición del método beforeSave.
	 * Cifrado de la clave antes de ser almacenada en la base de datos.
	 * @return boolean whether the saving should be executed. Defaults to true.
	 */
	public function beforeSave($event) {
		$this->owner = $this->getOwner();
		$this->owner->clave=$this->owner->hashPassword($this->owner->clave);
	}	
	
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function searchPorEmpresa()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.
		$owner = $this->getOwner();
		$criteria=new CDbCriteria;
	
		$criteria->compare('id',$owner->id);
		$criteria->compare('username',$owner->username,true);
		$criteria->compare('email',$owner->email,true);
		$criteria->compare('clave',$owner->clave,true);
		$criteria->compare('activo',1);
		$criteria->compare('nombres',$owner->nombres,true);
		$criteria->compare('apellidos',$owner->apellidos,true);
		$criteria->compare('tipo_identificacion_id',$owner->tipo_identificacion_id);
		$criteria->compare('identificacion',$owner->identificacion,true);
		$criteria->compare('telefono_fijo',$owner->telefono_fijo,true);
		$criteria->compare('celular',$owner->celular,true);
		$criteria->compare('direccion',$owner->direccion,true);
		//$criteria->compare('es_primer_administrador',0,true);
		
		$empresa=UsuarioHelper::obtenerEmpresaUsuarioAutenticado();
		if($empresa){
			$criteria->with = array('usuario_empresa');
			$criteria->compare( 'usuario_empresa.empresa_id', $empresa->id, true );
			$criteria->together = true;
		}
	
		return new CActiveDataProvider($owner, array(
				'criteria'=>$criteria,
		));
	}
	public function asignarRol($rol_id)
	{
		$owner = $this->getOwner();
		$command=Yii::app()->db->createCommand("INSERT INTO `usuario_rol`(`usuario_id`, `rol_id`) VALUES (:usuario_id,:rol_id)");
		$usuario_id=$owner->id;
		$command->bindParam(":usuario_id",$usuario_id,PDO::PARAM_INT);
		$command->bindParam(":rol_id",$rol_id,PDO::PARAM_INT);
		$command->execute();
	}
	public function obtenerPefilSistemaToString()
	{
		$owner = $this->getOwner();
		$arrayAuthRoleItems = Yii::app()->authManager->getAuthItems(2,$owner->id);
		$arrayKeys = array_keys($arrayAuthRoleItems);
		$perfil="Consulta";
		if($arrayKeys && count($arrayKeys)>0){
			$perfil = $arrayKeys[0];
		}
		return $perfil;
	}
	public function obtenerRolesEmpresaToString()
	{
		$owner = $this->getOwner();
		$id=$owner->id;
		$command=Yii::app()->db->createCommand("SELECT r.*  FROM `rol` r INNER JOIN `usuario_rol` ur ON ur.rol_id = r.id  WHERE ur.usuario_id = :usuario_id AND r.activo=1");
		$command->setFetchMode(PDO::FETCH_OBJ);
		$command->bindParam(":usuario_id",$id,PDO::PARAM_INT);
		$roles=$command->queryAll();
		$return="";
		foreach ($roles as $rol) {
			$return.=$rol->nombre.", ";
		}
		$return=substr($return,0,strlen($return)-2);
		return $return;
	}
}